/**
 * 专业信息菜单
 */
<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/manageClass/allRoomsInfo' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>专业信息</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 搜索筛选 -->
    <el-form :inline="true" :model="formInline" class="user-search">
      <el-form-item label="搜索：">
        <el-input size="small" v-model="formInline.sSubject" placeholder="请输入专业名称"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button size="small" type="primary" icon="el-icon-search" @click="search">搜索</el-button>
      </el-form-item>
       <el-form-item>
        <el-button size="small" type="primary" icon="el-icon-edit-outline" @click="handleStuCard">修改准考证需知</el-button>
      </el-form-item>
       <el-form-item>
        <el-button size="small" type="primary" icon="el-icon-plus" @click="handleEdit('新增专业')">新增专业</el-button>
      </el-form-item>
       <el-form-item>
        <el-button size="small" type="primary" icon="el-icon-plus" @click="handleEdit('新增考试科目')">新增考试科目</el-button>
      </el-form-item>
       <el-form-item>
        <el-select style="margin-left: 0.5vw" size="small" v-model="idCourseLabel" placeholder="请选择考试编号" @change="changeExamId">
        <el-option
          v-for="item in idCourseOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value">
        </el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <!--列表-->
   <el-table :data="listData"  :row-key="getRowKeys" border @expand-change="expandChange" :expand-row-keys="expands" style="width: 100%; margin-top: 20px" v-loading= "loading" >
    <el-table-column type="expand">
      <template slot-scope="props">
        <el-form  class="demo-table-expand">
          <template  v-for="item in props.row.subjects">
          <div :key="item.subId" class="form_div">
            <el-form-item label="科目编号：" :key="0">
            <span>{{item.subId}}</span>
            </el-form-item>
             <el-form-item label="考试科目：" :key="1">
            <span>{{item.subjectName}}</span>
            </el-form-item>
             <el-form-item label="考试日期：" :key="2">
            <span>{{item.sDate}}</span>
            </el-form-item>
              <el-form-item label="考试开始结束时间：" :key="3">
            <span>{{item.sStartTime+ ' ~ ' + item.sEndTime}}</span>
            </el-form-item>
            <div class="el_methods">
              <el-button type="primary"  @click="handleEdit(item)" icon="el-icon-edit" class="exam">修改考试信息</el-button>
              <el-button type="danger" icon="el-icon-error" class="exam" @click="deleteSubject(item,props.row)">删除考试</el-button>
            </div>
          </div>
          </template>
        </el-form>
      </template>
    </el-table-column>
     <el-table-column
      label="专业编号"
      prop="cid"
      align="center">
     </el-table-column>
     <el-table-column
       label="考试编号"
       prop="eno"
       align="center">
     </el-table-column>
     <el-table-column
       label="专业名称"
       prop="course"
       align="center">
     </el-table-column>
     <el-table-column align="center" label="操作" min-width="200">
        <template slot-scope="scope">
         <el-button-group>
          <el-button size="mini" icon="el-icon-edit" type="primary" @click="handleCourseEdit(scope.$index, scope.row)">编辑专业</el-button>
          <el-button size="mini" icon="el-icon-circle-close" type="danger" @click="deleteCourse(scope.$index, scope.row)">删除专业</el-button>
          </el-button-group>
        </template>
      </el-table-column>
  </el-table>
    <!-- 分页组件 -->
    <Pagination :child-msg="pageparm" @callFather="callFather"></Pagination>
    <!-- 准考证需知 编辑界面 -->
    <el-dialog :title="title" :visible.sync="stuCardVisible" width="50%" @click="closeDialog">
       <ue ref="ue"></ue>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeDialog">取消</el-button>
        <el-button size="small" type="primary" :loading="loading" @click="submitStuForm">保存</el-button>
      </div>
    </el-dialog>
     <!-- 考试科目 编辑界面 -->
    <el-dialog :title="title" :visible.sync="editFormVisible" width="35%" @click="closeDialog">
      <el-form label-width="125px" :model="editForm" ref="editForm">
        <el-form-item label="考试科目" prop="subjectName">
          <el-input size="small" v-model="editForm.subjectName" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="考试日期">
          <div class="block">
             <el-date-picker
               v-model="date"
               type="date"
               value-format="yyyy-MM-dd"
               placeholder="选择日期">
             </el-date-picker>
          </div>
        </el-form-item>
        <el-form-item label="考试开始结束时间">
          <el-time-picker
             is-range
             v-model="time"
             value-format="hh:mm:ss"
             range-separator="至"
             start-placeholder="开始时间"
             end-placeholder="结束时间"
             placeholder="选择时间范围">
          </el-time-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeDialog">取消</el-button>
        <el-button size="small" type="primary" :loading="loading" @click="submitForm('保存')">保存</el-button>
      </div>
    </el-dialog>
    <!-- 考试科目 新增界面 -->
    <el-dialog :title="title" :visible.sync="subjectFormVisible" width="35%" @click="closeDialog">
      <el-form label-width="125px" :model="subjectForm">
          <el-form-item label="考试编号" prop="eno">
          <el-input size="small" v-model="subjectForm.eno" auto-complete="off" placeholder="请输入考试编号"></el-input>
        </el-form-item>
         <el-form-item label="专业名称" prop="subjectName">
          <el-select v-model="subjectForm.pid" placeholder="选择需要添加考试的专业">
           <el-option
             v-for="item in idOptions"
             :key="item.value"
             :label="item.label"
             :value="item.value">
           </el-option>
           </el-select>
        </el-form-item>
        <el-form-item label="考试科目" prop="subjectName">
          <el-input size="small" v-model="subjectForm.subjectName" auto-complete="off" placeholder="请输入考试科目"></el-input>
        </el-form-item>
        <el-form-item label="考试日期">
          <div class="block">
             <el-date-picker
               v-model="date"
               type="date"
               value-format="yyyy-MM-dd"
               placeholder="选择日期">
             </el-date-picker>
          </div>
        </el-form-item>
        <el-form-item label="考试开始结束时间">
          <el-time-picker
             is-range
             v-model="time"
             value-format="hh:mm:ss"
             range-separator="至"
             start-placeholder="开始时间"
             end-placeholder="结束时间"
             placeholder="选择时间范围">
          </el-time-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeDialog">取消</el-button>
        <el-button size="small" type="primary" :loading="loading" @click="submitForm('添加')">添加</el-button>
      </div>
    </el-dialog>
    <!-- 专业 新增界面 -->
     <el-dialog :title="title" :visible.sync="majorVisible" width="35%" @click="closeDialog">
      <el-form label-width="125px" :model="courseForm">
        <el-form-item label="专业名称" prop="specialities">
          <el-input size="small" v-model="specialities" auto-complete="off" placeholder="请输入专业名称"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeDialog">取消</el-button>
        <el-button size="small" type="primary" :loading="loading" @click="submitForm('新增专业')">保存</el-button>
      </div>
    </el-dialog>
    <!-- 专业 编辑界面 -->
     <el-dialog :title="title" :visible.sync="courseFormVisible" width="35%" @click="closeDialog">
      <el-form label-width="125px" :model="courseForm" ref="addExamForm">
       <el-form-item label="专业编号" prop="cid">
          <el-input size="small" v-model="courseForm.cid" auto-complete="off" placeholder="请输入专业编号"></el-input>
        </el-form-item>
         <el-form-item label="考试编号" prop="eno">
          <el-input size="small" v-model="courseForm.eno" auto-complete="off" placeholder="请输入考试编号"></el-input>
        </el-form-item>
        <el-form-item label="专业名称" prop="course">
          <el-input size="small" v-model="courseForm.course" auto-complete="off" placeholder="请输入专业名称"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeDialog">取消</el-button>
        <el-button size="small" type="primary" :loading="loading" @click="submitForm('修改专业')">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getMajorExamInfo, modiExamInfo, deleteInfo, getExamProjectInfo, addSubjectInfo, modiCourseInfo, deleteCourseInfo, getAllMajorName, addMajor } from '../../../api/userOpe'
import Pagination from '../../../components/Pagination'
import ue from '../../../components/ue'

export default {
  data () {
    return {
      loading: true, // 显示加载
      editFormVisible: false, // 控制考试科目编辑页面显示与隐藏
      stuCardVisible: false, // 控制准考证需知编辑页面的显示与隐藏
      subjectFormVisible: false, // 添加考试界面
      courseFormVisible: false, // 编辑专业界面
      majorVisible: false, // 新增专业界面
      title: '编辑考试',
      // 列表展开参数
      expands: [],
      // excel 提交携带 token
      Myheaders: {
        USERTOKEN: sessionStorage.getItem('token')
      },

      // 点击选中的教室
      pointClassRooms: [],

      // 专业名称
      specialities: '',

      // 日历选择器
      date: '',

      // 时间选择器
      time: ['', ''],

      // 专业编号选择器数据
      idOptions: [],
      idData: { value: '', label: '' }, // for 循环 放进 idOption

      // 储存考试代码编号和名字 后续做成选择框
      examInfo: [],
      // 储存 eStatus = 1 的 考试编号
      activeData: '',
      idCourseOptions: [],
      idCourseData: { value: '', lable: '' },
      // 默认 idCourseLabel 值
      idCourseLabel: '',
      // 添加考试信息表单数据
      subjectForm: {
        eno: '',
        pid: '',
        subjectName: '',
        sDate: '',
        sStartTime: '',
        sEndTime: ''
      },
      // 专业编辑 表单
      courseForm: {
        cid: '',
        eno: '',
        course: ''
      },
      // 编辑功能 表单
      editForm: {
        subId: '',
        sDate: '',
        subjectName: '',
        sStartTime: '',
        sEndTime: ''
      },

      // 表单动态数据存储
      formInline: {
        page: 1,
        limit: 15,
        sSubject: ''
      },

      // 删除考试科目需要的参数
      subjectFormIds: {
        subId: '',
        cid: ''
      },

      rightData: [], // 教室所有数据
      listData: [], // 当前显示的数据
      // 分页参数
      pageparm: {
        currentPage: 1,
        pageSize: 15,
        total: 0
      }
    }
  },
  // 注册组件
  components: {
    Pagination,
    ue
  },
  mounted () {
    this.dateFormat()
    this.getData()
    this.getMajorName() // 到此页面就遍历一次专业导入选择器中
    setTimeout(() => {
      this.dataToSelect()
    }, 1000)
  },

  methods: {
    // 人性化处理 table 展开行默认展开行
    getRowKeys (row) {
      return row.cid
    },
    expandChange (row) {
      // console.log(row.cid, this.expands[0])
      if (row.cid === this.expands[0]) { // 判断是不是本身，如果点击的还是本身，则关闭，人性化
        this.expands = []
      } else {
        if (row.subjects) {
          this.expands = [] // 每次点击一个框，出自己以外其他的都不展示， 如果需要方便两个专业考试的对比那就删除本行
          if (row) {
            this.expands.push(row.cid)// 每次push进去的是每行的ID
          }
        } else {
          this.expands = []// 默认不展开
        }
      }
    },
    // 初次时间格式化
    dateFormat () {
      const date = new Date()
      const y = date.getFullYear() + '-'
      const m = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'
      const d = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
      const h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':'
      const min = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':'
      const sec = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
      this.date = y + m + d
      this.time[0] = h + min + sec
      this.time[1] = h + min + sec
    },
    // 获取专业考试信息
    getData () {
      getExamProjectInfo().then(res => {
        for (let i = 0; i < res.data.examInfoList.length; i++) {
          this.examInfo[i] = res.data.examInfoList[i]
        }
        console.log(this.examInfo)
        // 筛选 estatus为 1 的 考试数据
        this.activeData = res.data.examInfoList.filter((item) => {
          return item.eStatus === 1
        })
        console.log(this.activeData[0].eno)
        this.getMajorInfo(this.activeData[0].eno)
      }).catch((e) => {
        this.$message.warning('请求数据异常，请刷新页面重试！')
      })
    },
    // 获取正在进行的考试信息
    getMajorInfo () {
      getMajorExamInfo({ eno: this.activeData[0].eno }).then(res => {
        // console.log(res)
        if (res.code === 20000) {
          this.loading = false
          this.$message.success('各专业考试信息获取成功')
          // console.log(res.data.courseInfos)
          this.rightData = res.data.courseInfos
          // 分页数据切割
          this.cutData()
          this.pageparm.total = this.rightData.length
        }
      }).catch((e) => {
        this.loading = false
      })
    },
    // 获取全部专业名字
    getMajorName () {
      getAllMajorName().then(res => {
        // console.log(res.data.specialities)
        // 给专业名称选择器option赋值
        for (let i = 0; i < res.data.specialities.length; i++) {
          this.idData = {} // 重点 需要把 object初始化 {} 一下，不然赋值完以后，数组的值全部变成最后赋的值
          this.idData.value = res.data.specialities[i].pid
          this.idData.label = res.data.specialities[i].specialities
          this.idOptions[i] = this.idData
        }
        // console.log(this.idOptions)
      })
    },
    // 数据切割 分页
    cutData () {
      this.listData = this.rightData.slice((this.formInline.page - 1) * this.formInline.limit, (this.formInline.page * this.formInline.limit))
    },
    // 分页插件事件
    callFather (parm) {
      this.formInline.page = parm.currentPage
      this.formInline.limit = parm.pageSize
      this.cutData()
    },
    // 搜索事件 巧妙使用过滤器 filter
    search () {
      if (this.formInline.sSubject.trim() !== '') {
        this.listData = this.rightData.filter((item) => {
          return this.formInline.sSubject.trim() === item.course
        })
      } else {
        this.getData()
      }
    },
    // 给考试编号选择器option赋值
    dataToSelect () {
      // console.log(this.examInfo)
      // console.log(this.examInfo.length)
      for (let i = 0; i < this.examInfo.length; i++) {
        this.idCourseData = {} // 重点 需要把 object初始化 {} 一下，不然赋值完以后，数组的值全部变成最后赋的值
        this.idCourseData.value = this.examInfo[i].eno
        this.idCourseData.label = this.examInfo[i].eName
        this.idCourseOptions[i] = this.idCourseData
      }
      this.idCourseLabel = this.activeData[0].eName // 默认 label 赋值
      // console.log(this.idOptions)
    },
    // select 选择器被选中触发事件 传递value
    changeExamId (val) {
      if (val === this.activeData[0].eno) { // 选中的和上次相同则不刷新网页
        return true
      } else {
        this.activeData[0].eno = val
        // 每次切换格式化到第一页，人性化
        this.formInline.pageNum = 1
        this.pageparm.currentPage = 1
        // this.getInfo(this.activeData[0].eno)
        this.getMajorInfo(this.activeData[0].eno)
      }
    },
    // 修改考试信息编辑框和添加考试科目 ， 预处理
    handleEdit (val) {
      if (val === '新增专业') {
        this.title = '新增专业'
        this.majorVisible = true
      } else if (val === '新增考试科目') {
        this.getMajorName()
        this.title = '添加考试科目'
        this.subjectFormVisible = true
        this.subjectForm.eno = ''
        this.subjectForm.pid = ''
        this.subjectForm.subjectName = ''
      }
    },
    // 修改专业信息编辑框预处理
    handleCourseEdit (index, row) {
      // console.log(row)
      this.title = '编辑专业'
      this.courseFormVisible = true
      this.courseForm.cid = row.cid
      this.courseForm.eno = row.eno
      this.courseForm.course = row.course
    },
    // 准考证编辑预处理
    handleStuCard () {
      this.title = '修改准考证需知'
      this.stuCardVisible = true
    },
    // 保存考试信息，并刷新获取数据
    submitForm (val) {
      if (val === '保存') {
        // 发请求前先赋值
        this.editForm.sDate = this.date
        this.editForm.sStartTime = this.time[0]
        this.editForm.sEndTime = this.time[1]
        modiExamInfo(this.editForm).then(res => {
          this.loading = true
          if (res.message === 'OK') {
            this.editFormVisible = false
            this.loading = false
            this.$message.success('编辑考试成功！')
            this.getData()
          } else {
            this.loading = false
            this.$message.error('编辑失败，请重试！')
          }
        }).catch((e) => {
          this.loading = false
          this.editFormVisible = false
          this.$message.error('请求异常，请重试！')
        })
      } else if (val === '添加') {
        // 发请求前先赋值
        this.subjectForm.sDate = this.date
        this.subjectForm.sStartTime = this.time[0]
        this.subjectForm.sEndTime = this.time[1]
        console.log(this.subjectForm)
        addSubjectInfo(this.subjectForm).then(res => {
          this.loading = true
          if (res.message === 'OK') {
            this.subjectFormVisible = false
            this.loading = false
            this.$message.success('添加考试成功！')
            this.getData()
          } else {
            this.loading = false
            this.$message.error('添加失败，请重试！')
          }
        }).catch((e) => {
          this.loading = false
          this.subjectFormVisible = false
          this.$message.error('请求异常，请重试！')
        })
      } else if (val === '修改专业') {
        modiCourseInfo(this.courseForm).then(res => {
          this.loading = true
          if (res.message === 'OK') {
            this.courseFormVisible = false
            this.loading = false
            this.$message.success('编辑专业成功！')
            this.getData()
          } else {
            this.loading = false
            this.$message.error('编辑失败，请重试！')
          }
        }).catch((e) => {
          this.loading = false
          this.courseFormVisible = false
          this.$message.error('请求异常，请重试！')
        })
      } else if (val === '新增专业') {
        addMajor({ specialities: this.specialities }).then(res => {
          if (res.message === 'OK') {
            this.majorVisible = false
            this.loading = false
            this.$message.success('新增专业成功！')
            this.getMajorName() // 新增完专业就再遍历一次专业名称导入选择器中
            this.getData()
          } else {
            this.loading = false
            this.$message.error('新增失败，请重试！')
          }
        }).catch((e) => {
          this.loading = false
          this.majorVisible = false
          this.$message.error('请求异常，请重试！')
        })
      } else {
        return false
      }
    },
    // 删除专业 专业下的考试信息也会被一并删除
    deleteCourse (index, row) {
      console.log(row.cid)
      this.$confirm('此操作将永久删除该专业以及其下考试科目, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteCourseInfo({ cid: row.cid }).then(res => {
          console.log(res)
          if (res.message === 'OK') {
            this.$message.success('删除专业成功！')
            this.getData()
          } else {
            this.$message.error('删除专业失败！')
          }
        }).catch((e) => {
          this.$message.warning('请求数据异常，请刷新页面重试！')
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 删除单个考试专业下的考试科目 item 考试科目信息  row考试专业信息
    deleteSubject (item, row) {
      console.log(item.subId, row.cid)
      this.$confirm('此操作将永久删除该考试科目, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.subjectFormIds.subId = item.subId
        this.subjectFormIds.cid = row.cid
        deleteInfo(this.subjectFormIds).then(res => {
          if (res.message === 'OK') {
            this.$message.success('删除考试科目成功！')
            this.getData()
          } else {
            this.$message.error('删除考试科目失败！')
          }
        }).catch((e) => {
          this.$message.warning('请求数据异常，请刷新页面重试！')
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 批量上传至服务器
    submitUpload () {
      this.$refs.upload.submit()
    },

    // 保存准考证信息
    submitStuForm () {
      this.$refs.ue.submit()
      this.stuCardVisible = false
    },
    // 上传成功钩子,接收返回的后端数据
    handleSuccess (res) {
      // console.log(res)
      if (res.message === 'err') this.$message.error('您上传的文件有误！请重新上传，仅支持.xlsx/.xls文件')
      else {
        this.$message.success('文件上传至服务器成功！')
        // 重新获取数据并渲染
        this.getData()
      }
    },

    // 关闭编辑、添加弹出框
    closeDialog () {
      this.editFormVisible = false
      this.stuCardVisible = false
      this.subjectFormVisible = false
      this.courseFormVisible = false
      this.classRoomVisible = false
    }
  }
}
</script>

<style lang="stylus" scoped>
.user-search
  margin-top: 20px
.userRole
  width: 100%
.el-input
  width: 100%
.el-table, .el-table__expanded-cell
  opacity : 0.8
.el-button
   height : 33px !important
   margin-left : 10px
.upload-demo
  display: inline-block
  margin-left : 10px
.form_div
  border : 1px solid  #000000
  margin: -1px auto auto auto
  .el_methods
   width : 50%
   position: static
   transform : translate(0,-370%)
   margin-left  : 72%
  .exam
   padding-top : 9px
.el-form-item
 padding: 20px 0px 0px 0px
 margin : 0px
</style>
